package com.kai.utils;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

/**
 * Created By ShaoXikai on 2022/5/20
 */
public class MybatisUtil {
    // 将session对象的产生过程封装成一个工具类 提高代码的复用性
    private static SqlSessionFactory sqlSessionFactory;

    static {
        try {
            // 读取配置
            InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
            // 产生一个SqlSessionFactory对象
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static SqlSession getSqlSession() {
        // 返回SqlSession对象
        return sqlSessionFactory.openSession();
    }
}
